﻿using Microsoft.VisualStudio.TextTemplating;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading.Tasks;

namespace T4
{
    public class T4Helper
    {
        /// <summary>
        /// 生成Model
        /// </summary>
        /// <param name="tinfo"></param>
        /// <param name="ModelTemplate"></param>
        /// <returns></returns>
        public static string GenerateCode(ModelInfo minfo, string ModelTemplate)
        {

            string input = File.ReadAllText(ModelTemplate);

            var host = new CustomHost();
            host.TemplateFileValue = ModelTemplate;

            host.Session = new TextTemplatingSession();

            host.Session.Add("minfo", minfo);

            string output = new Engine().ProcessTemplate(input, host);


            StringBuilder errorWarn = new StringBuilder();

            foreach (CompilerError error in host.Errors)
            {
                errorWarn.Append(error.Line).Append(":").AppendLine(error.ErrorText);
            }
            if (!string.IsNullOrWhiteSpace(errorWarn.ToString()))
            {
                return errorWarn.ToString();
            }
            return output;

        }

    }
}
